package com.mianle.userapi.util;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.Random;

public class FileUtils {

    /**
     * 从request中获取文件进行处理  返回图片存储到本地的路径
     * @param request
     * @param filePath 文件存储路径 eg:/data/user_api_images/idcard 用户实名认证的路径地址
     *                            eg:/data/user_api_images/supplierin 商家入住存储图片地址
     * @return
     */
    public static  String getFilePath(HttpServletRequest request,String filePath){
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multiRequest.getFile(multiRequest.getFileNames().next());
        String fileName = file.getOriginalFilename();
        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
        try {
            uploadFile(file.getBytes(), filePath, newFileName);
        } catch (Exception e) {
            // TODO: handle exception
        }
        filePath=filePath+newFileName;
        return filePath;
    }



    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        out.write(file);
        out.flush();
        out.close();
    }


    /**
     * file文件转base64
     * @param filePath
     * @return
     */
    public String encryptToBase64(String filePath) {
        if (filePath == null) {
            return null;
        }
        try {
            byte[] b = Files.readAllBytes(Paths.get(filePath));
            return Base64.getEncoder().encodeToString(b);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

}
